package com.childmiles.gwt.client.ui;

import com.childmiles.gwt.client.domain.AwardWinner;
import com.childmiles.gwt.client.ui.MainActivity.MainDisplay;
import com.google.gwt.app.place.IsWidget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.HeadingElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class MainDisplayImpl extends Composite implements MainDisplay, IsWidget {

	private static MainDisplayUiBinder uiBinder = GWT
			.create(MainDisplayUiBinder.class);

	@UiTemplate("MainDisplay.ui.xml")
	interface MainDisplayUiBinder extends UiBinder<Widget, MainDisplayImpl> {
	}

	@UiField DeckPanel deckPanel;
	@UiField Image headerImage;
	//Login
	@UiField TextBox awardWinnerNameTextBox;
	@UiField Button okButton;
	//Awards
	@UiField HeadingElement title;
	@UiField Grid awardsTable;
    //Settings
	@UiField Button backToAwards;
	@UiField TextBox newArwardWinnerPhotoURLTextBox;
	@UiField Button changeAwardWinnerPhotoButton;
	@UiField Image currentAwardWinnerImage;

	private MainActivity activity;

	public MainDisplayImpl() {
		initWidget(uiBinder.createAndBindUi(this));
        Image awardWinnerPhoto = new Image();//currentAwardWinner.getPhotoUrl());
        awardWinnerPhoto.setTitle("Click for preferences");
        awardWinnerPhoto.addStyleName("awardWinnerImage");
        // 4 X 2 fixed grid
        awardsTable.resize(2, 4);
        awardsTable.setWidget(0,0, awardWinnerPhoto);
        showWidget(0);

/*
 * /Statistics
        
        //Title
        Label rankingsLabel = new Label("Rankings");
        rankingsLabel.addStyleName("title");
        loginPanel.add(rankingsLabel);
        //Content
        FlexTable statisticsPanel = new FlexTable();
        createStatisticsPanel(statisticsPanel);
        loginPanel.add(statisticsPanel);
        
        //Set focus
        DeferredCommand.addCommand(new Command() {
            public void execute() {
                awardWinnerNameTextBox.setFocus(true);
            }
        });
    private void createStatisticsPanel(final FlexTable container) {
//        TODO turn this into a table
//        container.add
        awardWinnerService.findAll(new AsyncCallback<List<AwardWinner>>() {
            public void onFailure(Throwable e) {
                throw new RuntimeException(e);
            }
            public void onSuccess(List<AwardWinner> awardWinners) {
                for (int i=0; i<awardWinners.size(); i++) {
                    final AwardWinner awardWinner = awardWinners.get(i);
                    //Header
                    Label nameLabel = new Label("Name");
                    nameLabel.setStyleName("tableHeader");
                    container.setWidget(0,0,nameLabel);
                    Label awardsLable = new Label("Awards");
                    awardsLable.setStyleName("tableHeader");
                    container.setWidget(0,1,awardsLable);

                    //Rows
                    Anchor awardWinnerNameLabel = new Anchor(awardWinner.getName());
                    awardWinnerNameLabel.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            loginAsAwardWinner(awardWinner.getName());                        }
                    });
                    container.setWidget(i+1,0,awardWinnerNameLabel);
                    Label totalNumberAwardsLabel = new Label("" + 
                            awardWinner.getAwards().getTotalNumberOfAwards());
                    totalNumberAwardsLabel.addStyleName("totalNumberOfRewardsLabel");
                    container.setWidget(i+1,1,totalNumberAwardsLabel);
                }
            }
        });
    }
 */
	}

	public void showAwards(AwardWinner currentAwardWinner) {
		title.setInnerText("Awards For " + currentAwardWinner.getName());
		currentAwardWinnerImage.setUrl(currentAwardWinner.getPhotoUrl());
		awardsTable.setWidget(0,0,new Image(currentAwardWinner.getPhotoUrl()));
        awardsTable.setWidget(0,1,new AwardPanel(1, currentAwardWinner.getAwards().get(1)));
        awardsTable.setWidget(0,2,new AwardPanel(2, currentAwardWinner.getAwards().get(2)));
        awardsTable.setWidget(0,3,new AwardPanel(3, currentAwardWinner.getAwards().get(3)));
        awardsTable.setWidget(1,0,new AwardPanel(4, currentAwardWinner.getAwards().get(4)));
        awardsTable.setWidget(1,1,new AwardPanel(5, currentAwardWinner.getAwards().get(5)));
        awardsTable.setWidget(1,2,new AwardPanel(6, currentAwardWinner.getAwards().get(6)));
        awardsTable.setWidget(1,3,new AwardPanel(7, currentAwardWinner.getAwards().get(7)));
	}

	public Widget asWidget() {
		return this;
	}

	public void setActivity(MainActivity activity) {
		this.activity = activity;
	}
	
	public void showActivityWidget(IsWidget widget) {
		//setWidget(widget.asWidget());
	}

	public void showWidget(int index) {
		deckPanel.showWidget(index);
	}

	@UiHandler({"headerImage", "okButton", "backToAwards", "changeAwardWinnerPhotoButton", "awardsTable"})
	public void onClick(ClickEvent event) {
		if (event.getSource().equals(backToAwards)) {
			activity.goBack();
		} else if (event.getSource().equals(changeAwardWinnerPhotoButton)) {
			activity.saveAwardWinnerPhoto(newArwardWinnerPhotoURLTextBox.getText());
		} else if (event.getSource().equals(headerImage)) {
			Window.Location.reload();
		} else if (event.getSource().equals(okButton)) {
			loginIfNotEmpty();
		} else if (event.getSource().equals(awardsTable)) {
			Cell cellForEvent = awardsTable.getCellForEvent(event);
	        if (cellForEvent == null) {
	            return;
	        }
	        int rowIndex = cellForEvent.getRowIndex();
	        int colIndex = cellForEvent.getCellIndex();
	        activity.onClick(rowIndex, colIndex, awardsTable.getWidget(rowIndex,colIndex));
		}
	}

	@UiHandler("awardWinnerNameTextBox")
	void onKeyDown(KeyDownEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			loginIfNotEmpty();
		}
	}

	private void loginIfNotEmpty() {
		if (!awardWinnerNameTextBox.getText().isEmpty()) {
			activity.loginAsAwardWinner(awardWinnerNameTextBox.getText());
		}
	}
}
